package com.lyl.springcloud.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author lylbell
 * @date 2021-05-28 16:40
 */
@Service
public class PaymentService {

    //正常访问
    public String paymentInfo_ok(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + ",paymentInfo_ok,id=" + id;
    }


    //停三秒访问
    @HystrixCommand(fallbackMethod = "paymentInfo_handler",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="5000")
    })
    public String paymentInfo_timeout(Integer id) {
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池：" + Thread.currentThread().getName() + ",paymentInfo_timeout,id=" + id;
    }

    public String paymentInfo_handler(Integer id) {
        return "线程池：" + Thread.currentThread().getName() + "服务器繁忙，请稍后再试,id="+id ;
    }

    //服务熔断
    @HystrixCommand(fallbackMethod = "paymentCircuitBreaker_fallback",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),//是否开启断路器
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "10"),//请求次数
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "10000"),//时间窗口期
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "60"),//失败率达到过少后跳闸
            //在10秒内，10次请求次数中失败率达到6次，就会跳闸。出现访问正常也会跳到降级处理的方法中，默认5s后恢复正常
    })
    public String paymentCircuitBreaker(Integer id) {
        if (id < 0) {
            throw new RuntimeException("id不能为负数");
        }
        String s = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t" + "流水号："+ s;
    }

    public String paymentCircuitBreaker_fallback(Integer id) {
        return "id不能为负数，请稍后重试，id=" + id;
    }
}
